package com.lincoln.framework.interceptor;

import com.lincoln.framework.common.WebUtils;
import com.lincoln.framework.utils.FrameworkLogger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * <h1>手机端返回url记录拦截器</h1>
 * 
 * <p>
 * 记录非ajax访问，用于点击后退
 * </p>
 * 
 * @author zwm
 */
public class MobileBackUrlInterceptor extends HandlerInterceptorAdapter {

	/**
	 * 日志
	 */
	private static FrameworkLogger logger = FrameworkLogger.initFrameworkLogger(MobileBackUrlInterceptor.class);

	public static final String SESSION_BACK_URL = "session_back_url";

	/**
	 * 不记录url
	 */
	private static List<String> filterPathList = new ArrayList<String>() {
		{
			this.add("goBack.htm");
			this.add("getSafeCode.htm");
			this.add("logout.htm");
			this.add("getCheckCodeImg.do");
		}
	};

	/**
	 * 记录访问url
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// ajax访问或者访问返回url不记录
		if (WebUtils.isAjaxRequest()) {
			return true;
		}
		for (String filterPath : filterPathList) {
			if (request.getRequestURL().toString().indexOf(filterPath) != -1) {
				return true;
			}
		}
		HttpSession session = request.getSession();
		List<String> backUrls = (List<String>) session.getAttribute(SESSION_BACK_URL);
		String backUrl = "";
		// 最后一条判断url是否改变，用于过滤页面刷新
		if (backUrls != null && backUrls.size() > 0) {
			int lastIndex = backUrls.size() - 1;
			String lastUrl = backUrls.get(lastIndex);
			if (lastUrl.indexOf(WebUtils.removeJsessionidOfUrl(request.getRequestURL().toString())) != -1) {
				backUrls.remove(lastIndex);
				backUrls.add(lastIndex, WebUtils.getRequestUrl());
				return true;
			}
		} else {
			backUrls = new ArrayList<String>();
		}
		backUrl = WebUtils.getRequestUrl();
		backUrls.add(backUrl);
		session.setAttribute(SESSION_BACK_URL, backUrls);
		return true;
	}

	/**
	 * 获取返回URL
	 */
	public static String popBackUrl(HttpServletRequest request) {
		HttpSession session = request.getSession();
		List<String> backUrls = (List<String>) session.getAttribute(SESSION_BACK_URL);
		String backUrl = getLastString(backUrls);
		session.setAttribute(SESSION_BACK_URL, backUrls);
		return backUrl;
	}

	/**
	 * 获取返回记录Url
	 * 
	 * @param backUrls
	 * @return String
	 */
	private static String getLastString(List<String> backUrls) {
		if (backUrls != null && backUrls.size() > 1) {
			String lastUrl = backUrls.get(backUrls.size() - 2);
			String nowUrl = backUrls.get(backUrls.size() - 1);
			backUrls.remove(backUrls.size() - 1);
			if (nowUrl.indexOf("isBack=1") != -1 && lastUrl.indexOf("toLogin.htm") != -1) {
				return getLastString(backUrls);
			}
			return lastUrl;
		}
		return null;
	}
}
